'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 服务器状态
 * @author sundbcn@gmail.com (sun debing)
 */

var mongoConnector = require('../libs/mongodb/mongoConnector');
/* jshint unused:false */
var serverStatusSchema = require('../schemas/serverStatusSchema.js');
var ServerStatus = mongoConnector().model('ServerStatus');
var dataApi = require('../libs/dataApi');
var configUtil = require('../util/configUtil');

var serverStatusModel = module.exports;

/**
 * 查询服务器状态
 */
serverStatusModel.getServerStatus = function (cb) {
    // 创建成功后
    function afterCreate(err, schema) {
        cb(err, schema);
    }

    // 查询成功后
    function afterFindOne(err, schema) {
        if (!!err) {
            return cb(err);
        }
        if (!!schema) {
            return cb(null, schema);
        } else {
            var game_config = configUtil.load('game');
            ServerStatus.create({
                server_id: game_config.server_id
            }, afterCreate);
        }
    }

    ServerStatus.findOne({}, afterFindOne);
};

/**
 * 查询游戏锁定状态
 */
serverStatusModel.isGameLocked = function (cb) {
    this.getServerStatus(function (err, schema) {
        if (!!err) {
            return cb(err, false);
        }
        if (!schema) {
            return cb(null, false);
        }

        cb(null, schema.game_locked);
    });
};

/**
 * 锁定游戏
 */
serverStatusModel.lockGame = function (cb) {
    ServerStatus.update({}, {
        game_locked: true
    }).exec(cb);
};

/**
 * 解锁游戏
 */
serverStatusModel.unLockGame = function (cb) {
    ServerStatus.update({}, {
        game_locked: false
    }).exec(cb);
};
